//
//  CMDDataProcessor.m
//  wAudioShare
//
//  Created by Anson on 14-4-3.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "CMDDataProcessor.h"

#import "WISInterfaces.h"
#import "wis.h"
#import "PersistableInfo.h"

@interface CMDDataProcessor (){
    NSString *ipUrl;
}

@property (nonatomic,strong) NSMutableDictionary *devDataListReturnExt;
@property (nonatomic,strong) NSMutableArray *devDataList;

@end
//负责发送命令和接收返回，返回给发送者
@implementation CMDDataProcessor

static CMDDataProcessor *sharSetDataInstance = nil;

+(CMDDataProcessor *) sharedInstance {
    
    if (!sharSetDataInstance)
    {
        sharSetDataInstance = [[CMDDataProcessor alloc] init];
    }
    return sharSetDataInstance;
}

- (void)getDeviceListResultDataWithDataRecivedBlock:(DataRecivedBlock) block
{
    self.dataRecivedBlock = block;
    if ([self getResultDevListData])
    {
        self.dataRecivedBlock([self getResultDevListData]); //这是缓存的数据
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self sendCMDToServer:WIS_CMD_V2_DEV_LIST_GET cmdLength:32 withData:(void *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String]];
          });
}

-(id)getResultDevListData
{
    return self.devDataListReturnExt;
}

//清除缓存的数据
- (void)clearDeviceListData
{
    self.devDataList = nil;
    self.devDataListReturnExt = nil;
}

- (NSArray *)getDataListFromJSONData:(NSData *)data {
    NSArray *devDataListRet = nil;
    if (data) {
        JSONDecoder *jd = [[JSONDecoder alloc] init];
        NSDictionary *jsonData = [jd objectWithData:data];
        NSString *state = [jsonData objectForKey:@"state"];
        if (state && [state.lowercaseString isEqualToString:@"success"]) {
            
            id devData = [jsonData objectForKey:@"data"];
            if (devData && [devData isKindOfClass:[NSArray class]]) {
                devDataListRet = (NSArray *)devData;
            }
        }
    }
    return devDataListRet;
    
}

- (void)revServerDevListData:(NSData *)data {
    NSLog(@"revServerDev:%d",[data length]);
    if (data)
    {
        self.devDataListReturnExt = nil;
        self.devDataList = nil;
//        NSArray *jsonDataList = [self getDataListFromJSONData:data];
//        NSString * str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
        
        NSMutableDictionary *jsonDataDic = [[data objectFromJSONData] mutableCopy];
        
        NSLog(@"[data objectFromJSONData]:%@",[data objectFromJSONData]);
        NSArray *jsonDataList = jsonDataDic[@"data"];
        
        
        if (jsonDataList)
        {
            self.devDataList = [NSMutableArray arrayWithArray:jsonDataList];
//            self.devDataListReturnExt = [NSArray arrayWithArray:jsonDataList];
        }
        self.devDataListReturnExt = jsonDataDic;
        self.dataRecivedBlock(self.devDataListReturnExt);//一直crash在这
    }
}

- (void)updateDevStatusChangeData:(NSData *)data {
    
    if (data) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            NSArray *jsonDataList = [self getDataListFromJSONData:data];
            if (jsonDataList && jsonDataList.count > 0) {
                
                for (NSDictionary *updateDev in jsonDataList) {
                    
                    NSString *zIDOfUpdateDev = [updateDev objectForKey:@"ZID"];
                    for (NSInteger i=0; i<self.devDataList.count; i++) {
                        
                        NSDictionary *item = [self.devDataList objectAtIndex:i];
                        if ([[item objectForKey:@"ZID"] isEqualToString:zIDOfUpdateDev]) {
                            [self.devDataList replaceObjectAtIndex:i withObject:updateDev];
                            break;
                        }
                        
                    }
                }
                
                [self.devDataListReturnExt setValue:[NSArray arrayWithArray:self.devDataList] forKey:@"data"];
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DEV_STATE_CHANGE_GET object:nil userInfo: @{NOTIFICATION_USERINFO_UPDATEDATA: jsonDataList}];
            }
        });
    }
    
}

-(void)sendCMDId:(int)cmdid cmdLength:(int)length withData:(void *)cmdData callRecivedBlock:(DataRecivedBlock)bolck
{
    if ([self sendCMDToServer:cmdid cmdLength:length withData:cmdData] == 0) {
         self.dataRecivedBlock = bolck;
    }
}

- (void)revServerDataCall:(NSData *)data {
    NSDictionary *retJsonData = nil;
    JSONDecoder *jd = [[JSONDecoder alloc] init];
    if (data)
    {
        retJsonData = [jd objectWithData:data];
        NSLog(@"retJsonData:%@",retJsonData);
    }
    if (self.dataRecivedBlock)
    {
        self.dataRecivedBlock(retJsonData);
    }
    /*
    @try {
        NSDictionary *retJsonData = [jd objectWithData:data];
        if (self.dataRecivedBlock) self.dataRecivedBlock(retJsonData);
    }
    @catch (NSException *exception) {
        //if (self.dataRecivedBlock) self.dataRecivedBlock(nil);
    }
    @finally {
        
    }*/
}

- (NSInteger)sendCMDToServer:(int)cmdid cmdLength:(int)length withData:(void *)cmdData
{
    if ([GlobalService sharedInstance].curOperationDeviceUUID.length == 0) {
        return -1;
    }
    
    return [WISInterfaces wis_send_private_cmd:[GlobalInfo sharedInstance].m_CmdSock cmdId:cmdid data:cmdData len:length uuid:(char *)[[GlobalService sharedInstance].curOperationDeviceUUID UTF8String]];
}

-(void)setDataRecivedBlock:(DataRecivedBlock)dataRecivedBlock
{
    _dataRecivedBlock = dataRecivedBlock;
}

- (NSInteger)sendCGIURLCMDWithData:(void *)cmdData callRecivedBlock:(DataRecivedBlock)bolck {
    
    if ([GlobalService sharedInstance].curOperationDeviceUUID.length == 0) return -1;
    
    NSInteger result = [WISInterfaces wis_send_cgi_url_cmd:[GlobalInfo sharedInstance].m_CmdSock uuid:(char *)[[GlobalService sharedInstance].curOperationDeviceUUID UTF8String] msgid:0 urlData:cmdData];
    if (result == 0) {
        self.dataRecivedBlock = bolck;
    }
    return result;
}

@end
